from cdsay import user
from cdsay.user.form import loginForm, registerForm, userForm
from cdsay.user.models import userModel
from django.shortcuts import render_to_response
import datetime
import md5

def login(request):
    if request.method == 'POST':
        form = loginForm(request.POST)
        if form.is_valid():
            try :
                user = userModel.objects.get(email=request.POST.get('email'))
                if md5.new(request.POST.get('password')).hexdigest() == user.password :
                    return render_to_response('base.html', {'form': form})
                else:
                    form.passwordIsWrong = 'Y'
            except :
                form.userNotExist = 'Y'
    else:
        form = loginForm()
    return render_to_response('login.html', {'form': form})

def register(request):
    if request.method == 'POST':
        form = userForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.save()
            return render_to_response('index.html', {'form': form})
        form = registerForm(request.POST)
        if form.is_valid():
            try :
                user = userModel.objects.get(email=request.POST.get('email'))
                if user.id > 0:
                    if md5.new(request.POST.get('password')).hexdigest() == md5.new(request.POST.get('repassword')).hexdigest() :
                        userModel.email=request.POST.get('email')
                        userModel.password=md5.new(request.POST.get('password')).hexdigest()
                        registerForm.save(userModel);
                        return render_to_response('index.html', {'form': form})
                    else:
                        form.passwordIsWrong = 'Y'
            except :
                if md5.new(request.POST.get('password')).hexdigest() == md5.new(request.POST.get('repassword')).hexdigest() :
                    model = userModel(
                                      email=request.POST.get('email', ''),
                                      password=md5.new(request.POST.get('password')).hexdigest(),
                                      photo=request.POST.get('password', 'photopath'),
                                      createtime=datetime.datetime.now(),
                                      )
                    model.save()
                    return render_to_response('index.html', {'form': form})
                
    else:
        form = registerForm()
    return render_to_response('register.html', {'form': form})
